package org.example.virtualsensors;

import org.example.virtualsensors.entity.EmsItem;
import org.example.virtualsensors.entity.dto.LoginRequest;
import org.example.virtualsensors.entity.model.EmsQuantity;
import org.example.virtualsensors.entity.model.Host;
import org.example.virtualsensors.entity.model.Sensor;
import org.example.virtualsensors.service.AuthorizationService;
import org.example.virtualsensors.service.SensorRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@SpringBootApplication
@EnableScheduling
public class SimulatorApplication implements CommandLineRunner {
    private final SensorRegistrationService registrationService;


    @Autowired
    public SimulatorApplication(SensorRegistrationService registrationService) {
        this.registrationService = registrationService;
    }

    public static void main(String[] args) {
        SpringApplication.run(SimulatorApplication.class, args);
    }
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void reportRealTimeData(){
        new Thread(()->{
            while(true){
                String data = String.format("""
        [
                                      "com.sunwe.emview.core.model.FenceModel",
                                      {
                                        "id": null,
                                        "collectionTime": [
                                          "java.util.Date", %d
                                        ],
                                        "itemKey": "111",
                                        "itemgroupKey": "fence1",
                                        "itemgroupSn": "fence",
                                        "tempVal": %.1f,
                                        "humiVal": %.1f,
                                        "arm": "布防",
                                        "alarm": "防区报警",
                                        "devOnline": "在线",
                                        "devTamper": "正常",
                                        "devDcLow": "正常",
                                        "devAcLoss": "正常",
                                        "fenceAlarm": "正常",
                                        "fenceSlack": "正常",
                                        "fenceCut": "正常",
                                        "fenceDcVal": %.1f
                                      }
                                    ]
    """, System.currentTimeMillis(),
                        new Random().nextFloat() * (30.0f - 15.0f) + 15.0f, // 随机生成15到30之间的温度
                        new Random().nextFloat() * (30.0f - 15.0f) + 15.0f, // 随机生成15到30之间的温度
                        new Random().nextFloat() * (80.0f - 40.0f) + 40.0f); // 随机生成40到80之间的湿度

                redisTemplate.opsForValue().set("fence/111/REALTIMEDATA_CACHE", data);
                if (redisTemplate == null) System.out.println("redisTemplate为空");
                else {
                    String s = redisTemplate.opsForValue().get("fence/111/REALTIMEDATA_CACHE");
                    System.out.println(s);
                };
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

//    @Value("host-register-url")
    String hostRegistrationUrl="http://localhost:58080/gateway/itemGroup/register";
//    @Value("主机心跳接口")
    String hostHeartbeatUrl="http://localhost:58080/gateway/itemGroup/heartbeat";
//    @Value("传感器注册接口")
    String sensorRegistrationUrl="http://localhost:58080/gateway/realtime/upload";
//    @Value("传感器发送实时数接口")
    String sensorDataReportUrl="http://localhost:58080/gateway//history/upload";


    public void boot(){
        reportRealTimeData();

        //注册一个虚拟主机
        Host host = new Host();
        initHost(host);

        //注册一个虚拟传感器
        Sensor sensor = new Sensor();
        initSensor(sensor);

        //为虚拟传感器添加监测量
        EmsQuantity emsQuantity = new EmsQuantity();
        sensor.getEmsItem().getQuantities().add(emsQuantity);
        initQuantity(sensor.getEmsItem(),emsQuantity);

        //发送心跳
        host.heartbeat(hostHeartbeatUrl);

        try {
            //向监测平台注册信息
            host.registerHost(hostRegistrationUrl);

            //注册传感器信息
//            sensor.registerSensor(sensorRegistrationUrl);

            //发送实时数据
            String jsonData = newRealTimeData();
//            sensor.reportRealtimeData(sensorDataReportUrl,jsonData);

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private String newRealTimeData() {
        // todo

        String data = String.format("""
        [
           "com.sunwe.emview.core.model.Th802RtDataModel",
           {
             "id": null,
             "collectionTime": [
               "java.util.Date", %d
             ],
             "itemKey": "11",
             "itemgroupKey": null,
             "itemgroupSn": null,
             "t": %.1f,
             "h": %.1f
           }
         ]
    """, System.currentTimeMillis(),
                new Random().nextFloat() * (30.0f - 15.0f) + 15.0f, // 随机生成15到30之间的温度
                new Random().nextFloat() * (80.0f - 40.0f) + 40.0f); // 随机生成40到80之间的湿度
        return data;
    }

    private void initQuantity(EmsItem emsItem,EmsQuantity emsQuantity) {
        emsQuantity.setId("U001");
        emsQuantity.setAlarmColor("red");
        emsQuantity.setAlarmValue(50f);
        emsQuantity.setAlarmTimes(0);
        emsQuantity.setData(20f);
        emsQuantity.setUpperLimit(100f);
        emsQuantity.setLowerLimit(0f);
        emsQuantity.setQuantityName("emsQuantity");
        emsQuantity.setItemgroupKey("2");
        emsQuantity.setClopenStatus(1);
        emsQuantity.setItemgroupId("sss");
        emsQuantity.setStatus(1);
        emsQuantity.setItemgroupSn("10000002");
        emsQuantity.setUnitName("te");
        emsQuantity.setStatus(1);
        emsQuantity.setType(1);
        emsQuantity.setItemKey(emsItem.getItemKey());
        emsQuantity.setQuantityKey(1);
        emsQuantity.setId(emsItem.getId());
        emsQuantity.setItemId(emsItem.getId());
    }

    private void initSensor(Sensor sensor) {
        sensor.getEmsItem().setItemModel("yd2010");
        StringBuilder sb = new StringBuilder();
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        sensor.getEmsItem().setItemName("wendu");
        sensor.getEmsItem().setX("0");
        sensor.getEmsItem().setY("0");
        sensor.getEmsItem().setAlarmTimes(0);
        sensor.getEmsItem().setItemRs485Id(String.valueOf(3));
        sensor.getEmsItem().setFaultTimes(0);
        sensor.getEmsItem().setItemIfaceId("Sensor3");
        sensor.getEmsItem().setItemType(String.valueOf(0));
        sensor.getEmsItem().setClassification("CFN_DLJC");
        sensor.getEmsItem().setItemUserModel("EMS-0121N/0120W");
        int i = random.nextInt(10000);
        sensor.getEmsItem().setItemKey(String.valueOf(i));
        sensor.getEmsItem().setItemgroupKey("3");
        sensor.getEmsItem().setNumData(0);
        sensor.getEmsItem().setQuantEvent(0);
        sensor.getEmsItem().setRunControl(0);
        sensor.getEmsItem().setStatus(1);
        sensor.getEmsItem().setType("NUMERIC");
        sensor.getEmsItem().setItemgroupId("100");
        sensor.getEmsItem().setClassification("CFN_DLJC");
        sensor.getEmsItem().setItemgroupSn("10000003");
        sensor.getEmsItem().setAllAlarmConfirm(1);
        sensor.getEmsItem().setItemNo(10);
        sensor.getEmsItem().setItemIfaceId("Sensor1");
        sensor.getEmsItem().setQuantEvent(1);
        sensor.getEmsItem().setItemUserModel("EMS-0343YD/0343WLB/0343WLD2/...");
        sensor.getEmsItem().setItemUserName("三相电量仪");
        sensor.getEmsItem().setIsSplit(0);
        sensor.getEmsItem().setModType("-");
    }

    private void initHost(Host host) {
        host.itemgroup.setItemgroupModel("EMS3000");
        host.itemgroup.setId(UUID.randomUUID().toString());
        System.out.println(host.itemgroup.getId());
        host.itemgroup.setAppAddress("1.1.1.1"); //todo 需要解决监控平台无法成功设置这个ip
        host.itemgroup.setItemgroupName("virtualHost");
        host.itemgroup.setX("5");
        host.itemgroup.setY("5");
        host.itemgroup.setItemgroupKey("3");
        host.itemgroup.setStatus(3);
        host.itemgroup.setAlarmNum(0);
        host.itemgroup.setDownlineTimes(0);
        host.itemgroup.setFaultNum(0);
        host.itemgroup.setLastCheckTime(LocalDateTime.now());
        host.itemgroup.setLastNoticeTime(LocalDateTime.now());
        host.itemgroup.setLastOnlineTime(LocalDateTime.now());
        host.itemgroup.setOnlineDuration(270L);
        host.itemgroup.setEventNoticeConfigId("9ceaac1c35d34cbc9a9f8aa1d507bbb2");
        host.itemgroup.setNetworkConfigId("542f6adb6c6f4958b931f043373901eb");
        host.itemgroup.setCreator("admin");
        host.itemgroup.setBimultiple("1");
        host.itemgroup.setWidth("0");
        host.itemgroup.setHeight("0");
        host.itemgroup.setLevelCode("100100");
        host.itemgroup.setItemgroupSn("10000003");
    }

    @Override
    public void run(String... args) throws Exception {


        boot();


//        reportRealTimeData();
//
//
//
//
//        AuthorizationService.getLicense();
//        // 注册虚拟主机
//        LoginRequest.HostRegistrationRequest hostRequest = new LoginRequest.HostRegistrationRequest();
//        hostRequest.setItemgroup_name("VirtualHost");
//        hostRequest.setItemgroup_model("VH001");
//        hostRequest.setItemgroup_sn("SN123456");
//        hostRequest.setApp_address("192.168.1.100");
//        hostRequest.setCreator("admin");
//        hostRequest.setItemgroup_key("VH001_KEY");
//
//        // 注册5个虚拟传感器
//        String[] sensorKeys = {"S001", "S002", "S003", "S004", "S005"};
//        for (String key : sensorKeys) {
//            LoginRequest.SensorRegistrationRequest sensorRequest = new LoginRequest.SensorRegistrationRequest();
//            sensorRequest.setItem_name("Sensor_" + key);
//            sensorRequest.setItem_model("SM001");
//            sensorRequest.setItemgroup_sn("SN123456");
//            sensorRequest.setItemgroup_key("VH001_KEY");
//            sensorRequest.setItem_key(key);
//            sensorRequest.setCreator("admin");
//            registrationService.registerSensor(sensorRequest);
//        }
//
//        System.out.println("虚拟主机和传感器注册完成");
    }
}

